#!/bin/bash

# 卸载 Docker
echo "正在卸载旧版本的 Docker..."
sudo yum remove -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin docker-ce-rootless-extras > /dev/null 2>&1
sudo rm -rf /var/lib/docker
sudo rm -rf /var/lib/containerd
echo "Docker 卸载完成."

# 设置阿里云仓库
echo "正在设置阿里云镜像源..."
curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo > /dev/null 2>&1
yum install -y yum-utils > /dev/null 2>&1
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo > /dev/null 2>&1
yum makecache fast > /dev/null 2>&1
echo "阿里云镜像源设置完成."

# 安装 Docker
echo "正在安装 Docker..."
sudo yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin > /dev/null 2>&1
echo "Docker 安装完成."

# 启动 Docker
echo "正在启动 Docker 服务..."
sudo systemctl enable --now docker > /dev/null 2>&1
echo "Docker 服务已启动."

# 验证 Docker
echo "正在验证 Docker 安装..."
if sudo docker version &> /dev/null; then
    echo "Docker 版本:"
    sudo docker version --format '{{.Server.Version}}'
else
    echo "Docker 安装失败，请检查日志."
    exit 1
fi

echo "运行 hello-world 测试镜像..."
if sudo docker run hello-world &> /dev/null; then
    echo "Docker 运行成功!"
else
    echo "Docker 运行测试镜像失败，请检查日志."
    exit 1
fi